#ifndef VARPOOL
#define VARPOOL

#include <stdlib.h>
#include <malloc.h>
#include <string.h>

#include "poly.h"

// 变量类型
typedef struct _Variable
{
    char name[20];
    Poly *poly;
    struct _Variable *next;
} Var;

// 变量池类型，即由变量组成的链表
typedef struct
{
    Var *head;
} VarPool;

// 初始化Var类型
Var *NewVar(const char *name, Poly *poly)
{
    Var *var = (Var *)malloc(sizeof(Var));
    strcpy(var->name, name);
    var->poly = poly;
    var->next = NULL;
    return var;
}

// 初始化VarPool类型
VarPool *NewPool()
{
    VarPool *pool = (VarPool *)malloc(sizeof(VarPool));
    pool->head = NewVar("", NULL);
    pool->head->next = NULL;
    return pool;
}

// 将变量放入变量池
void PutVar(VarPool *pool, Var *var)
{
    Var *p;
    for (p = pool->head; p->next; p = p->next)
    {
        if (!strcmp(p->next->name, var->name))
        {
            ClearPoly(p->next->poly);
            free(p->next->poly);
            p->next->poly = var->poly;
            free(var);
            break;
        }
    }
    if (!p->next)
    {
        p->next = var;
        var->next = NULL;
    }
}

// 按变量名从变量池中获取变量
Var *GetVar(VarPool *pool, const char *name)
{
    for (Var* v = pool->head; v->next; v = v->next)
    {
        if (!strcmp(v->next->name, name))
        {
            return v->next;
        }
    }
    return NULL;
}

void ClearPool(VarPool *pool)
{
    Var *temp;
    while (pool->head)
    {
        temp = pool->head;
        pool->head = temp->next;
        ClearPoly(temp->poly);
        free(temp->poly);
        free(temp);
    }
}

#endif